<template>
	<view class="user" :class="isDark?'dark':''" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view>
			<view class="header gpt-header" :style="[{height:CustomBar + 'px'}]" :class="scrollTop>40?'goScroll':''">
				<view class="cu-bar" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}" >
					<view class="action" @tap="back">
						<text class="cuIcon-back"></text>
					</view>
					<view class="content" :style="[{top:StatusBar + 'px'}]">
						<text class="text-bold">{{name}}</text>
					</view>
					<view class="action">
						<view class="cu-avatar round"  @tap="showModal" data-target="chatInfo" :style="avatarstyle" v-if="avatarstyle!=''"></view>
						<view class="cu-avatar round" v-else>
							<text class="home-noLogin"></text>
						</view>
					</view>
				</view>
			</view>
			<view class="gpt-bg" v-if="!isDark">
				<image src="./style/gpt-bg.png"></image>
			</view>
			<view class="cu-chat cu-chat-gpt" >
				<view class="cu-item"  :style="[{padding:NavBar + 'px 0px 0px 0px'}]"></view>
				<!-- <view class="more-msg">
					<text class="text-blue" @tap="loadMore">{{moreText}}</text>
				</view> -->
				<view class="gpt-nodata-info" v-if="msgList.length==0">
					<view class="gpt-nodata-info-ico">
						<image src="./style/gpt.png"></image>
					</view>
					<view class="gpt-nodata-info-tips">
						{{$t('sygpt.chat.useaichatfun')}}
					</view>
					<view class="gpt-nodata-info-box">
						<view class="gpt-nodata-info-main" @tap="msg=$t('sygpt.chat.overcomeprocras')" hover-class="gpt-nodata-info-hover">
							{{$t('sygpt.chat.overcomeprocras')}}
						</view>
					</view>
					<view class="gpt-nodata-info-box">
						<view class="gpt-nodata-info-main" @tap="msg=$t('sygpt.chat.writeautumntale')" hover-class="gpt-nodata-info-hover">
							{{$t('sygpt.chat.writeautumntale')}}
						</view>
					</view>
					<view class="gpt-nodata-info-box">
						<view class="gpt-nodata-info-main" @tap="msg=$t('sygpt.chat.genrandomnum')" hover-class="gpt-nodata-info-hover">
							{{$t('sygpt.chat.genrandomnum')}}
						</view>
					</view>
				</view>
				<view class="cu-info gpt-cu-info" v-if="msgList.length>0">
					{{$t('sygpt.chat.latest100msg')}}
				</view>
				<block v-for="(item,index) in msgList" :key="index">
					<view class="cu-item " :class="item.isAI==0?'self':''">
						<view class="main">
							<view class="content shadow break-all gpt-content" :class="item.isAI==0?'bg-blue light':''">
								<mp-html :content="item.text" :selectable="true" :show-img-menu="true"  :scroll-table="true" :markdown="true"/>
							</view>
						</view>
						<view class="date">
							{{formatDate(item.created)}}
						</view>
					</view>
				</block>
				<view class="cu-item" v-if="isWaiting==1">
					<view class="main">
						<view class="content shadow break-all">
							{{$t('sygpt.chat.aithinking')}}
						</view>
					</view>
				</view>
			</view>
			<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
				<template v-if="isWaiting==0">
					<textarea class="msg-input"  :adjust-position="false" :focus="false" maxlength="-1" auto-height  :placeholder="$t('sygpt.chat.singlereqconsum')+price+currencyName" @focus="InputFocus" @blur="InputBlur" v-model="msg"/>
					<button class="cu-btn bg-blue light" @tap="sendMsg()">{{$t('global.send')}}</button>
				</template>
				<template v-if="isWaiting==1">
					<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10" placeholder="$t('sygpt.chat.aithinking')"/>
					<button class="cu-btn bg-blue light">{{$t('sygpt.chat.waiting')}}</button>
				</template>
			</view>
			<view class="cu-modal" :class="modalName=='chatInfo'?'show':''">
				<view class="cu-dialog">
					<view class="cu-bar bg-white justify-end">
						<view class="content"><text class="text-bold">{{name}}</text></view>
						<view class="action" @tap="hideModal">
							<text class="cuIcon-close text-red"></text>
						</view>
					</view>
					<view class="user-edit-header">
						<image :src="avatar"></image>
						<view class="gpt-tips-intro">{{intro}}</view>
					</view>
					<view class="cu-bar bg-white justify-center">
						<view class="action">
							<button class="cu-btn bg-blue light" @tap="goHistory()">
								{{$t('sygpt.chat.historymsg')}}
							</button>
							<button class="cu-btn bg-red margin-left" @tap="gptChatDelete()">
								{{$t('sygpt.chat.resetchat')}}
							</button>
						</view>
					</view>
				</view>
			</view>
			<!--加载遮罩-->
			<view class="loading" v-if="isLoading==0">
				<view class="loading-main">
					<image src="style/loading.gif"></image>
				</view>
			</view>
			<!--加载遮罩结束-->
		</view>
	</view>
</template>

<script>
	import { localStorage } from '@/js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar:this.StatusBar +  this.CustomBar,
				AppStyle:this.$store.state.AppStyle,
				InputBottom: 0,
				id:0,
				name:$t('sygpt.chat.unlargemodel'),
				moreText:$t('common.getmore'),
				isWaiting:0,
				toid:0,
				avatar:"",
				userInfo:null,
				token:"",
				avatarstyle:"",
				msg:"",
				page:1,
				
				msgList:[],
				uid:"",
				
				msgLoading:null,
				lastTime:0,
				
				group:"",
				
				
				modalName:"",
				lastid:0,
				
				isLoading:0,
				
				price:"",
				intro:"",
				currencyName:"",
				
				scrollTop:0,
			};
		},
		onPageScroll(res){
			var that = this;
			that.scrollTop = res.scrollTop;
		},
		onShow() {
			var that = this
			if(localStorage.getItem('userinfo')){
				that.userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.uid = that.userInfo.uid;
				that.group = that.userInfo.group;
			}
		},
		onReachBottom() {
		    //触底后执行的方法，比如无限加载之类的
			var that = this;
			//到底部后，重新变成第一页，开始加载数据
			that.page = 1;
		},
		onBackPress() {
			
		},
		onUnload() {
			
		},
		onLoad(res) {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			uni.request({
				url:that.$API.SPset(),
				method:'GET',
				dataType:"json",
				success(res) {
					that.currencyName = res.data.assetsname;
				},
				fail(error) {
					
				}
			})
			if(res.id){
				that.id = res.id;
				that.getGptInfo();
				that.getMsgList();
				// that.setRead();
				// that.msgLoading = setInterval(() => {
				//  that.getMsgList(false);
				// }, 3000);
			}
			// if(that.type==1){
			// 	that.getGroupInfo(that.chatid);
			// }
			// #ifdef APP-PLUS
			uni.onKeyboardHeightChange(res => {
				//监听软键盘的高度 
				//当点击软键盘自带的收起按钮的时候也就是会隐藏软键盘 这时候监听到的软键盘的高度就是0 、
				//让输入框取消焦点 这时候再去输入内容的时候 输入框就会弹起
				if (res.height == 0) {
					that.InputBottom = 0;
				}else{
					that.InputBottom = res.height;
				}
			});
			// #endif
		},
		methods: {
			back(){
				var that = this;
				clearInterval(that.msgLoading);
				that.msgLoading = null
				uni.navigateBack({
					delta: 1
				});
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				//second = ("0" + date.getSeconds()).slice(-2);
				// 拼接
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				// 返回
				return result;
			},
			InputFocus(e) {
				this.isOwO = false;
				this.InputBottom = e.detail.height;
			},
			InputBlur(e) {
				this.InputBottom = 0;
			},
			previewImage(image) {
				var imgArr = [];
				imgArr.push(image);
				//预览图片
				uni.previewImage({
					urls: imgArr,
					current: imgArr[0]
				});
			},
			getMsgList(){
				var that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				// else{
				// 	用户加载更多数据时，不再加载数据
				// 	if(page > 1){
				// 		return false;
				// 	}
				// }
				that.$Net.request({
					url: that.$API.gptLastMsg(),
					data:{
						"token":token,
						"gptid":that.id,
						"limit":100,
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						uni.stopPullDownRefresh();
						that.isLoad=0;
						if(res.data.code==1){
							var list = res.data.data;
							list = list.reverse();
							that.msgList = list;
							
						}
						that.isLoading=1;
						setTimeout(() => {
							uni.pageScrollTo({
								duration: 0,
								scrollTop: 99999999
							})
						},200)
					},
					fail: function(res) {
						uni.stopPullDownRefresh();
						that.isLoad=0;
						that.isLoading=1;
					}
				})
			},
			getGptInfo(){
				var that = this;
				var data = {
					"id":that.id,
				}
				
				that.$Net.request({
					url: that.$API.gptInfo(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							var gptInfo = res.data.data;
							that.avatarstyle = "background-image:url("+gptInfo.avatar+");"
							that.avatar = gptInfo.avatar;
							that.name = gptInfo.name;
							that.price = gptInfo.price;
							that.intro =  gptInfo.intro;
						}
					},
					fail: function(res) {
					}
				});
			},
			sendMsg(){
				var that = this;
				var token = "";
				if(that.msg==""){
					return false;
				}
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				if(that.msg.length>1500){
					uni.showToast({
						title: that.$t('sygpt.chat.maxcharof1500'),
						icon: 'none'
					})
					return false
				}
				var data={
					"gptid":that.id,
					"token":token,
					"msg":that.msg,
				}
				//添加一个新字段
				var curtime = Date.parse(new Date());
				var msg ={
					"created": curtime / 1000,
					"text":that.msg,
					"isAI": 0,
					"uid": that.uid,
					"userJson": that.userInfo
				}
				that.msgList.push(msg);
				setTimeout(() => {
					uni.pageScrollTo({
						duration: 0,
						scrollTop: 99999999
					})
				},100)
				that.msg = "";
				that.isWaiting = 1;
				that.$Net.request({
					url: that.$API.gptSendMsg(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						that.isWaiting = 0;
						if(res.data.code==1){
							var msg ={
								"created": res.data.data.created,
								"text":res.data.data.text,
								"isAI": 1,
								"uid": that.uid,
								"userJson": that.userInfo
							}
							that.msgList.push(msg);
							setTimeout(() => {
								uni.pageScrollTo({
									duration: 0,
									scrollTop: 99999999
								})
							},200)
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						that.isWaiting = 0;
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			goHistory(){
				var that = this;
				uni.navigateTo({
					url: '/pages/plugins/sy_gpt/history?id='+that.id
				});
			},
			ToCopy(text) {
				var that = this;
				// #ifdef APP-PLUS
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({ //提示
							title: that.$t('common.copysuccess')
						})
					}
				});
				// #endif
				// #ifdef H5 
				let textarea = document.createElement("textarea");
				textarea.value = text;
				textarea.readOnly = "readOnly";
				document.body.appendChild(textarea);
				textarea.select();
				textarea.setSelectionRange(0, text.length) ;
				uni.showToast({ //提示
					title: that.$t('common.copysuccess')
				})
				var result = document.execCommand("copy") 
				textarea.remove();
				
				// #endif
			},
			upload(){
				let that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					clearInterval(that.msgLoading);
					that.msgLoading = null
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				uni.chooseImage({
					count: 6, 
					sourceType: ['album', 'camera'], 
				    success: function (res) {
						uni.showLoading({
							title: that.$t('common.upload')
						});
						const tempFilePaths = res.tempFilePaths;
						for(let i = 0;i < tempFilePaths.length; i++) {
							const uploadTask = uni.uploadFile({
							  url : that.$API.upload(),
							  filePath: tempFilePaths[i],
							  name: 'file',
							  formData: {
							   'token': token
							  },
							  success: function (uploadFileRes) {
								  let count = 0;
								  count++;
								  if(count==tempFilePaths.length){
									  setTimeout(function () {
										uni.hideLoading();
									  }, 1000);
								  }
									var data = JSON.parse(uploadFileRes.data);
									//var data = uploadFileRes.data;
									// uni.showToast({
									// 	title: data.msg,
									// 	icon: 'none'
									// })
									if(data.code==1){
										that.sendURL(1,data.data.url);
									}
								},fail:function(){
									
								}
							});
						}
					}
				})
			},
			sendURL(type,url){
				var that = this;
				var token = "";
				if(that.url==""){
					return false;
				}
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				var data={
					"chatid":that.chatid,
					"token":token,
					"url":url,
					"type":type,
				}
				that.$Net.request({
					url: that.$API.sendMsg(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							that.getMsgList();
							that.msg = "";
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			markHtml(text){
				var that = this;
				text = that.replaceAll(text,"<","&lt;");
				text = that.replaceAll(text,">","&gt;");
				// #ifdef APP-PLUS || H5
				var owoList=that.owoTextList;
				for(var i in owoList){
					if(that.replaceSpecialChar(text).indexOf(owoList[i].data) != -1){
						text = that.replaceAll(that.replaceSpecialChar(text),owoList[i].data,"<img src='/"+owoList[i].icon+"' class='tImg' />")
					}
				}
				// #endif
				return text;
			},
			goChatInfo(){
				
			},
			replaceSpecialChar(text) {
				if(!text){
					return false;
				}
				text = text.replace(/&quot;/g, '"');
				text = text.replace(/&amp;/g, '&');
				text = text.replace(/&lt;/g, '<');
				text = text.replace(/&gt;/g, '>');
				text = text.replace(/&nbsp;/g, ' ');
				return text;
			},
			replaceAll(string, search, replace) {
				return string.split(search).join(replace);
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal() {
				this.modalName = null
			},
			gptChatDelete(){
				var that = this;
				var token = "";
				this.modalName = null;
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					"id":that.id,
					"token":token
				}
				uni.showModal({
				    title: that.$t('sygpt.chat.delmsgclear'),
				    success: function (res) {
				        if (res.confirm) {
				            uni.showLoading({
				            	title: that.$t('common.loadmore')
				            });
				            that.$Net.request({
				            	url: that.$API.gptChatDelete(),
				            	data:data,
				            	header:{
				            		'Content-Type':'application/x-www-form-urlencoded'
				            	},
				            	method: "get",
				            	dataType: 'json',
				            	success: function(res) {
				            		setTimeout(function () {
				            			uni.hideLoading();
				            		}, 1000);
				            		uni.showToast({
				            			title: res.data.msg,
				            			icon: 'none'
				            		})
				            		if(res.data.code==1){
										that.back();
				            		}
				            	},
				            	fail: function(res) {
				            		setTimeout(function () {
				            			uni.hideLoading();
				            		}, 1000);
				            		uni.showToast({
				            			title: that.$t('common.networkfail'),
				            			icon: 'none'
				            		})
				            	}
				            })
				        }
				    }
				});
			},
		}
	}
</script>

<style>
page{
  padding-bottom: 100upx;
}
.cu-bar.foot{
	z-index: 998;
}
</style>
